package com.sea.supply.controller;


import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.product.service.ChannelService;
import com.sea.supply.entity.ProductPrice;
import com.sea.supply.service.ProductPriceService;
import com.sea.supply.service.SupplierService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/supply/productPrice")
public class ProductPriceController {

    @Autowired
    private ProductPriceService productPriceService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ChannelService channelService;

    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        //供应商
        model.addAttribute("supplier", supplierService.findByCnd(null));
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));

        return "/sea/supply/productPrice/main";
    }

    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model) {
        //供应商
        model.addAttribute("supplier", supplierService.findByCnd(null));
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/supply/productPrice/add";
    }
    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model,@RequestParam("id")Integer id) {
        //供应商
        model.addAttribute("supplier", supplierService.findByCnd(null));
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        model.addAttribute("productPrice",productPriceService.findById(id));
        return "/sea/supply/productPrice/edit";
    }
    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     ProductPrice productPrice
                                     ) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<ProductPrice> list = productPriceService.findByCnd(productPrice);
        PageInfo<ProductPrice> page = new PageInfo<ProductPrice>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }



    /**
     * 保存
     * @param productPrice
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(ProductPrice productPrice) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != productPrice && productPriceService.save(productPrice) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前数据不能重复!");
            return result;
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(ProductPrice productPrice) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != productPrice && productPriceService.usave(productPrice) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前数据不能重复!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importClubDo(Model model,@RequestParam("productMember")String productMember, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                productPriceService.importSku(file.getInputStream(), fileName,productMember);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("删除失败！");
        try{
            if (null != id && productPriceService.delete(id) > 0) {
                result.setOk(true).setMsg("删除成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }



    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response,ProductPrice productPrice) {
        List<ProductPrice> list = productPriceService.findByCnd(productPrice);
        String[] title = {"供货商名称","渠道","SKU","币种","最新含税价格","不含税价格","最新含税价格(RMB)","不含税价格(RMB)","税率","更新时间"};
        String fileName = "供应商报价信息" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "供应商报价信息";
        String[][] content = new String[list.size()][10];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            ProductPrice map = list.get(i);
            content[i][0] = map.getProductSupplierName();
            content[i][1] = map.getProductChannelName();
            content[i][2] = map.getProductSku();
            content[i][3] = map.getProductMoneyType();
            content[i][4] = map.getProductPrice()+"";
            content[i][5] = map.getProductUnitPrice()+"";
            content[i][6] = map.getProductPriceCny()+"";
            content[i][7] = map.getProductUnitPriceCny()+"";
            content[i][8] = map.getProductPercent()+"%";
            content[i][9] = map.getModifyTime()+"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/exportHistory", method = RequestMethod.GET)
    @ResponseBody
    public void exportHistory(HttpServletResponse response,ProductPrice productPrice) {
        List<ProductPrice> list = productPriceService.exportHistory(productPrice);
        String[] title = {"供货商名称","渠道","SKU","价格","变动日期","备注"};
        String fileName = "供应商报价历史信息" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "供应商报价历史信息";
        String[][] content = new String[list.size()][6];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            ProductPrice map = list.get(i);
            content[i][0] = map.getProductSupplierName();
            content[i][1] = map.getProductChannelName();
            content[i][2] = map.getProductSku();
            content[i][3] = map.getProductPrice()+"";
            content[i][4] = map.getModifyTime()+"";
            content[i][5] = map.getProductRemark();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
